package ctrutil

import (
	"cloud_worm/util/third/ucapital"
	"github.com/astaxie/beego/logs"
	"fmt"
	"cloud_worm/util/umodels/mysqldb/dbmanager"
	"strings"
	"cloud_worm/util/umodels/mysqldb"
	"time"
)

type CapitalDeal struct {
	IP 		string
	WormId 	string
}

func (c *CapitalDeal) TryAddMachineOrApplyOne() error {
	mData, err := ucapital.CapitalInst.Cap.QueryOneMachine(c.IP)
	if err != nil {
		logs.Error(fmt.Sprintf("query '%s' capital error: %s", c.IP, err.Error()))
		return err
	}

	appId, err := c.dealApply(mData)
	if err != nil {
		logs.Error(fmt.Sprintf("deal application`%s` error: %s", c.IP, err.Error()))
		return err
	}

	if err := c.dealMachine(appId, c.IP, c.WormId, mData); err != nil {
		logs.Error(fmt.Sprintf("deal machine`%s` error: %s", c.IP, err.Error()))
	}

	return nil
}

func (c *CapitalDeal) dealApply(mData *ucapital.MachineItem) (int64, error) {
	app := &dbmanager.Application{Name: mData.AppName}
	if err := app.Read("name"); err != nil {
		if !strings.Contains(err.Error(), mysqldb.NoMysqlRow) {
			return 0, err
		}

		// 没有，执行插入
		app.Status = mysqldb.StatusValid
		app.Created = time.Now().Unix()
		app.Updated = app.Created
		return app.Insert()
	}

	return app.Id, nil
}

func (c *CapitalDeal) dealMachine(appId int64, ip string, wormId string, mData *ucapital.MachineItem) error {
	ma := &dbmanager.Machine{Ip: ip}
	if err := ma.Read("ip"); err != nil {
		if !strings.Contains(err.Error(), mysqldb.NoMysqlRow) {
			return err
		}

		ma.ApplyId = appId
		ma.Ip = ip
		ma.WormId = wormId
		ma.Created = time.Now().Unix()
		ma.Updated = ma.Created
		ma.Status = mysqldb.StatusValid
		return ma.Insert()
	}

	if ma.ApplyId != appId || ma.WormId != wormId {
		logs.Debug(fmt.Sprintf("update machine app_id and worm_id for `%s`", ip))
		ma.ApplyId = appId
		ma.WormId = wormId
		ma.Updated = time.Now().Unix()
		return ma.Update("apply_id", "worm_id", "updated")
	}

	return nil
}